from flask import Blueprint, request, jsonify
from app.services.string_util_service import StringGenerator
from app.utils.validators import validate_generation_request

bp = Blueprint('api', __name__, url_prefix='/api')


@bp.route('/generate', methods=['POST'])
def generate_string():
    """生成字符串API端点"""
    try:
        # 获取请求数据
        data = request.get_json()

        # 验证请求数据
        errors = validate_generation_request(data)
        if errors:
            return jsonify({'error': errors}), 400

        # 提取参数
        length = data.get('length')
        char_type = data.get('char_type')
        prefix = data.get('prefix', '')
        suffix = data.get('suffix', '')
        custom_chars = data.get('custom_chars', '')

        # 生成字符串
        result, history_id = StringGenerator.generate_and_save(
            length, char_type, prefix, suffix, custom_chars
        )

        return jsonify({
            'result': result,
            'history_id': history_id,
            'message': '字符串生成成功'
        })

    except ValueError as e:
        return jsonify({'error': str(e)}), 400
    except Exception as e:
        return jsonify({'error': '服务器内部错误'}), 500


@bp.route('/history', methods=['GET'])
def get_history():
    """获取生成历史API端点"""
    try:
        limit = min(int(request.args.get('limit', 10)), 100)  # 限制最大100条
        offset = int(request.args.get('offset', 0))

        history = StringGenerator.get_history(limit, offset)

        return jsonify({
            'history': [item.to_dict() for item in history],
            'total': len(history)
        })

    except Exception as e:
        return jsonify({'error': '服务器内部错误'}), 500


@bp.route('/history/<int:history_id>', methods=['GET'])
def get_history_item(history_id):
    """获取特定历史记录API端点"""
    try:
        history = StringGenerator.get_history_by_id(history_id)

        if not history:
            return jsonify({'error': '历史记录不存在'}), 404

        return jsonify(history.to_dict())

    except Exception as e:
        return jsonify({'error': '服务器内部错误'}), 500


@bp.route('/history', methods=['DELETE'])
def clear_history():
    """清空历史记录API端点"""
    try:
        StringGenerator.clear_history()
        return jsonify({'message': '历史记录已清空'})

    except Exception as e:
        return jsonify({'error': '服务器内部错误'}), 500


@bp.route('/char-types', methods=['GET'])
def get_char_types():
    """获取支持的字符类型API端点"""
    char_types = list(StringGenerator.CHAR_TYPE_MAP.keys())
    return jsonify({'char_types': char_types})
